/**
 * 
 */
package org.sword.lang;

import java.io.File;

import org.apache.log4j.Logger;

import jodd.http.HttpResponse;
import jodd.util.net.MimeTypes;

/**
 * 
 * @author chengn
 * @date 2014年12月12日
 */
public class HttpUtils {
	private static Logger logger = Logger.getLogger(HttpUtils.class);

	public static final int timeout = 10;

	/**
	 * post 请求
	 * 
	 * @param url
	 * @return
	 */
	public static String post(String url) {
		return post(url, "");
	}

	/**
	 * post请求
	 * 
	 * @param url
	 * @param data
	 * @return
	 */
	public static String post(String url, String data) {
		return httpPost(url, data);
	}

	/**
	 * get请求
	 * 
	 * @param url
	 * @return
	 */
	public static String get(String url) {
		return httpGet(url);
	}

	/**
	 * post 请求
	 * 
	 * @param url
	 * @param data
	 * @return
	 */
	private static String httpPost(String url, String data) {
		try {
			logger.info(url);
			jodd.http.HttpRequest httpRequest = jodd.http.HttpRequest.post(url).contentType(MimeTypes.MIME_TEXT_HTML);
			HttpResponse response = httpRequest.bodyText(data).send();
			return response.body() != null ? response.bodyText() : null;
		} catch (Exception e) {
			logger.error("post请求异常，" + e.getMessage() + "\n post url:" + url);
			e.printStackTrace();
		}
		return null;
	}

	/**
	 * 上传文件
	 * 
	 * @param url
	 *            URL
	 * @param file
	 *            需要上传的文件
	 * @return
	 */
	public static String postFile(String url, File file) {
		return postFile(url, null, file);
	}

	/**
	 * 上传文件
	 * 
	 * @param url
	 *            URL
	 * @param name
	 *            文件的post参数名称
	 * @param file
	 *            上传的文件
	 * @return
	 */
	public static String postFile(String url, String name, File file) {
		try {
			jodd.http.HttpRequest httpRequest = jodd.http.HttpRequest.post(url).contentType(MimeTypes.MIME_TEXT_HTML);
			httpRequest.form(name, file);
			HttpResponse response = httpRequest.send();
			return response.body() != null ? response.bodyText() : null;
		} catch (Exception e) {
			logger.error("postFile请求异常，" + e.getMessage() + "\n post url:" + url);
			e.printStackTrace();
		}
		return null;
	}

	/**
	 * 下载文件
	 * 
	 * @param url
	 *            URL
	 * @return 文件的二进制流，客户端使用outputStream输出为文件
	 */
	public static byte[] getFile(String url) {
		try {
			jodd.http.HttpRequest httpRequest = jodd.http.HttpRequest.get(url);
			HttpResponse response = httpRequest.send();
			return response.toByteArray();
		} catch (Exception e) {
			logger.error("postFile请求异常，" + e.getMessage() + "\n post url:" + url);
			e.printStackTrace();
		}
		return null;
	}

	/**
	 * 发送get请求
	 * 
	 * @param url
	 * @return
	 */
	private static String httpGet(String url) {
		try {
			jodd.http.HttpRequest httpRequest = jodd.http.HttpRequest.get(url);
			HttpResponse response = httpRequest.send();
			return response.body() != null ? response.bodyText() : null;
		} catch (Exception e) {
			logger.error("get请求异常，" + e.getMessage() + "\n get url:" + url);
			e.printStackTrace();
		}
		return null;
	}
}
